<?php


namespace app\helper;


use app\constant\UserConst;
use app\constant\WxUserConst;
use app\model\AdminUserVip;
use app\model\AppWxUser;
use DateTime;
use DateTimeZone;
use think\Db;

class VipHelper
{
    /**
     * 增加会员时间
     * @param $uid
     * @param $time integer
     * @return bool
     */
    public static function addVipTime($uid, $time)
    {
        $userVipModel = AdminUserVip::get($uid);
        $model = AppWxUser::get($uid);
        if(!$model){
            return false;
        }
        if (!$userVipModel) {
            $userVipModel = AdminUserVip::create(['tid'=>$model->tid,'id'=>$uid,'expiration_time'=>(new DateTime())->format('Y-m-d H:i:s')]);
        }
        Db::startTrans();
        try {
            $date = new DateTime($userVipModel->expiration_time);
            $date->setTimestamp($date->getTimestamp() + $time);
            $date->setTimezone(new DateTimeZone('Asia/Shanghai'));
            $dateStr = $date->format('Y-m-d H:i:s');
            $userVipModel->setAttr('expiration_time', $dateStr);
            $done = $userVipModel->allowField(true)->save();
            if ($done) {
                $model->setAttr('type',WxUserConst::TYPE_VIP);
                $updateDone = $model->allowField(true)->save();
                if(!$updateDone){
                    throw new \Exception();
                }
            }else{
                throw new \Exception();
            }
            Db::commit();
            TokenHelper::updateToken($uid);
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }
}